package com.flaremars.picker;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.flaremars.picker.fragments.BBSFragment;
import com.flaremars.picker.fragments.CardsFragment;
import com.flaremars.picker.fragments.RadarFragment;
import com.flaremars.picker.utils.FileUtils;
import com.flaremars.picker.utils.StringUtils;
import com.flaremars.picker.views.NavigationBarView;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private static final int FRAGMENT_INDEX_BBS = 1;
    private static final int FRAGMENT_INDEX_LEAFCARDS = 2;

    private static final int REQUEST_CODE_GET_FROM_CAMERA = 1;
    private static final int REQUEST_CODE_GET_FROM_FILE = 2;
    private static final SimpleDateFormat PHOTO_NAME_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);

    private String tempPhotoPath = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();

    }

    private void initViews() {

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton getFromFile = (FloatingActionButton) findViewById(R.id.fab_picture_with_file);
        getFromFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPictureFromFile();
            }
        });
        FloatingActionButton getFromCamera = (FloatingActionButton) findViewById(R.id.fab_picture_with_camera);
        getFromCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPictureFromCamera();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        List<Fragment> fragments = initFragments();

        viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        viewPager.setCurrentItem(1);

        //获取 “加” 按钮，重写其点击事件
        final FloatingActionsMenu actionsMenu = (FloatingActionsMenu) findViewById(R.id.fam_actions_menu);
        actionsMenu.getChildAt(2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewPager.getCurrentItem() == FRAGMENT_INDEX_BBS) {
                    actionsMenu.collapse();
                    Toast.makeText(MainActivity.this,"发布帖子",Toast.LENGTH_SHORT).show();
                } else  {
                    actionsMenu.toggle();
                }
            }
        });

        NavigationBarView navigationBarView = (NavigationBarView) findViewById(R.id.main_navigation_bar);
        navigationBarView.setViewPager(viewPager);
    }

    private List<Fragment> initFragments() {
        List<Fragment> fragments = new ArrayList<>(3);
        fragments.add(new RadarFragment());
        fragments.add(new BBSFragment());
        fragments.add(new CardsFragment());
        return fragments;
    }

    private void getPictureFromCamera() {
        setPicturePath();
        final File file = new File(tempPhotoPath);
        final Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra("output", Uri.fromFile(file));
        intent.putExtra("return-data", false);
        startActivityForResult(intent, REQUEST_CODE_GET_FROM_CAMERA);
    }

    private void setPicturePath() {

        final File directory = FileUtils.INSTANCE.getPhotosDirectory(this);
        String tempPhotoName = PHOTO_NAME_FORMAT.format(new Date()) + ".jpg";
        assert directory != null;
        tempPhotoPath = directory.getPath() + File.separator + tempPhotoName;
    }

    private void getPictureFromFile() {
        final Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        intent.addCategory("android.intent.category.OPENABLE");
        try {
            this.startActivityForResult(Intent.createChooser(intent, "选择一张植物图片"), REQUEST_CODE_GET_FROM_FILE);
        }
        catch (ActivityNotFoundException ex) {
            Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String targetPicturePath = "";
            boolean needRotate = false;
            if (requestCode == REQUEST_CODE_GET_FROM_CAMERA) {
                needRotate = true;
                File file = new File(tempPhotoPath);
                if (file.exists()) {
                    targetPicturePath = tempPhotoPath;
                }
            } else if (requestCode == REQUEST_CODE_GET_FROM_FILE) {
                needRotate = false;
                String path = FileUtils.INSTANCE.getPath(this, data.getData());
                if (path != null) {
                    targetPicturePath = path;
                }
            }
            if (!StringUtils.INSTANCE.isEmpty(targetPicturePath)) {
                Intent intent = new Intent(this,PreTreatmentActivity.class);
                intent.putExtra(PreTreatmentActivity.ARGUMENT_PICTURE_PATH,targetPicturePath);
                intent.putExtra(PreTreatmentActivity.ARGUMENT_NEED_ROTATE,needRotate);
                startActivity(intent);
            } else {
                Toast.makeText(MainActivity.this,"can't get a picture!",Toast.LENGTH_SHORT).show();
            }
        }
    }

    private class MyFragmentPagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragments;

        public MyFragmentPagerAdapter(FragmentManager fragmentManager,List<Fragment> fragments) {
            super(fragmentManager);
            this.fragments = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.nav_personal_info) {

        } else if (id == R.id.nav_ranking) {

        } else if (id == R.id.nav_setting) {

        } else if (id == R.id.nav_delete_cache) {
            FileUtils.INSTANCE.deleteFile(FileUtils.INSTANCE.getPhotosDirectory(this));
            Toast.makeText(this,"清除完成",Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
